﻿using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Migrations;
using System.Data.Entity.ModelConfiguration.Conventions;
using BusinessObjects.Models;
using EFRepository.Migrations;


namespace EFRepository
{
    public class EFContext : DbContext
    {
        private static string connectionString =
            "Data Source=192.168.1.102,1433;Network Library=DBMSSOCN;Initial Catalog=EFRepository.EFContext;User ID=tuser;";

        public EFContext()
            : base(connectionString)
        {
            Configuration.ProxyCreationEnabled = false;
        }

        public DbSet<User> Users { get; set; }
        public DbSet<Dish> Dishes { get; set; }
        public DbSet<Department> Departments { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<Provider> Providers { get; set; }

        public static void SetConnectionString(string connection)
        {
            connectionString = connection;
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            modelBuilder.Entity<User>().HasRequired(p => p.Department)
                        .WithMany(b => b.Users)
                        .HasForeignKey(p => p.DepartmentId);
            modelBuilder.Entity<Provider>().HasRequired(p => p.Department)
                        .WithRequiredDependent(b => b.Provider);
            modelBuilder.Entity<Order>().HasRequired(p => p.User).
                         WithMany(b => b.Orders).HasForeignKey(p => p.UserId);
            modelBuilder.Entity<OrderItem>().HasRequired(p => p.Order)
                        .WithMany(b => b.OrderItems)
                        .HasForeignKey(p => p.OrderId);
            modelBuilder.Entity<OrderItem>().HasRequired(p => p.Dish)
                        .WithRequiredDependent(b => b.OrderItem);

            modelBuilder.Entity<Dish>().HasRequired(p => p.Provider)
                        .WithMany(b => b.Dishes)
                        .HasForeignKey(p => p.ProviderId);
        }
    }

    public class CustomInitializer : IDatabaseInitializer<EFContext>
    {
        #region IDatabaseInitializer<MasterDetailContext> Members

        public void InitializeDatabase(EFContext context)
        {
            var cfg = new Configuration();
            cfg.TargetDatabase = new DbConnectionInfo(context.Database.Connection.ConnectionString,
                                                      "System.Data.SqlClient");

            var dbMigrator = new DbMigrator(cfg);
            dbMigrator.Update();
        }

        #endregion
    }
}